import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus_seven/pages/home/index.dart';
import 'package:flutter_enjoy_plus_seven/pages/mine/index.dart';
import 'package:flutter_enjoy_plus_seven/utils/Emitter.dart';
import 'package:flutter_enjoy_plus_seven/utils/TokenManager.dart';

class TabsPage extends StatefulWidget {
  const TabsPage({super.key});

  @override
  State<TabsPage> createState() => _TabsPageState();
}

class _TabsPageState extends State<TabsPage> {
  // 当前选中的索引
  int _currentIndex = 0;

  @override
  void initState() {
    super.initState();
    // 初始化 token
    tokenManager.init();
    // 注册事件监听
    regiterEventBus();
  }

  /// 注册事件监听
  regiterEventBus() {
    // 监听 LogoutEvent 事件
    eventBus.on<LogoutEvent>().listen((event) {
      // 跳转登录页
      Navigator.pushNamed(context, '/login');
    });
  }

  /// 父组件，定义 更新 tabs 索引 的方法，用于在子组件中调用
  updateIndexFn(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    // 脚手架组件
    return Scaffold(
      // 顶部导航标题，写到 Tabs 页面中，确保页面标题不一样
      // appBar: AppBar(
      //   title: const Text('享+社区'), // 标题
      //   centerTitle: true, // 居中(兼容ohos端)
      // ),
      // 页面主体
      body: IndexedStack(
        index: _currentIndex,
        children: [
          const HomePage(),
          MinePage(updateIndexFn: updateIndexFn),
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        selectedItemColor: const Color(0xff5592af),
        unselectedItemColor: const Color(0xFF434242),
        selectedFontSize: 12,
        unselectedFontSize: 12,
        currentIndex: _currentIndex,
        onTap: (int index) {
          setState(() {
            _currentIndex = index;
          });
        },
        items: [
          BottomNavigationBarItem(
            icon: Image.asset(
              'assets/tabs/home_default.png',
              width: 24,
              height: 24,
            ),
            activeIcon: Image.asset(
              'assets/tabs/home_active.png',
              width: 24,
              height: 24,
            ),
            label: '首页',
          ),
          BottomNavigationBarItem(
            icon: Image.asset(
              'assets/tabs/my_default.png',
              width: 24,
              height: 24,
            ),
            activeIcon: Image.asset(
              'assets/tabs/my_active.png',
              width: 24,
              height: 24,
            ),
            label: '我的',
          ),
        ],
      ),
    );
  }
}
